<!--
 * @description 定向福利-编辑页
 * @author dumeng
 * @date 2021/7/28
 -->
<template>
  <div class="derectional-update-page">
    <el-scrollbar class="classify-scrollbar">
      <div class="create-title">编辑</div>
      <el-form ref="form" class="create-form" :model="form" :rules="rules" label-width="180px">
        <el-form-item label="发放名称" prop="giveName">
          <el-input v-model.trim="form.giveName" placeholder="请输入发放名称" />
        </el-form-item>
        <el-form-item label="选择商城" prop="storeName">
          <el-radio-group v-model="form.storeName" disabled>
            <el-radio v-for="(item,index) in mallTypes" :key="index" :label="item.id">{{ item.name }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="福利类型" prop="classifType">
          <el-radio-group v-if="form.storeName===1" v-model="form.classifType" disabled>
            <el-radio v-for="(item, index) in ptTypes" :key="index" :label="item.id">{{ item.name }}
            </el-radio>
          </el-radio-group>
          <el-radio-group v-if="form.storeName===2" v-model="form.classifType" disabled>
            <el-radio v-for="(item, index) in jdTypes" :key="index" :label="item.id">{{ item.name }}
            </el-radio>
          </el-radio-group>
          <el-radio-group v-if="form.storeName===3" v-model="form.classifType" disabled>
            <el-radio v-for="(item, index) in hfTypes" :key="index" :label="item.id">{{ item.name }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <ptflb
          v-if="form.classifType==='0'"
          :id="form.id"
          ref="ptflbForm"
          :data="subForm"
          @useRangeChange="useRangeChange"
        />
        <ptdhq v-if="form.classifType==='1'" :id="form.id" ref="ptdhqForm" :data="subForm" />
        <jdflb v-if="form.classifType==='2'" :id="form.id" ref="jdflbForm" :data="subForm" />
        <ptthq v-if="form.classifType==='7'" :id="form.id" ref="ptthqForm" :data="subForm" />
        <hfflb v-if="form.classifType==='8'" :id="form.id" ref="hfflbForm" :data="subForm" />
        <template v-if="form.classifType==='0'&& useRange !== '2'">
          <el-form-item label="专区名称" prop="areaName">
            <el-input v-model="form.areaName" placeholder="请输入专区名称" />
          </el-form-item>
          <el-form-item label="专区图片" prop="imageType">
            <el-radio-group v-model="form.imageType">
              <el-radio label="0">模板库选择</el-radio>
              <el-radio label="1">自定义</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="form.imageType === '0'" label="">
            <div class="add-image" style="width: 50%; padding-bottom: 0;">
              <div class="add-image-title">
                <span>请选择模板</span>
                <el-button type="text" @click="templateVisible = true">{{ form.areaImg ? '重新选择' : '点击选择' }}</el-button>
              </div>
              <div class="add-image-main">
                <el-image :src="upload4area.view + form.areaImg || ''">
                  <div slot="error" class="image-slot">
                    <template>
                      <div class="icon-wrap">
                        <i class="el-icon-plus avatar-uploader-icon" />
                      </div>
                    </template>
                  </div>
                </el-image>
              </div>
            </div>
          </el-form-item>
          <el-form-item v-else>
            <el-row :gutter="10">
              <el-col :span="12">
                <div class="add-image">
                  <div class="add-image-title">
                    <span>上传专区图片</span>
                  </div>
                  <image-upload
                    ref="upload4home"
                    :key="upload4area.imagecropperKey"
                    v-model="form.areaImg"
                    :preview-id="form.areaImg"
                    :forever="true"
                    :width="705"
                    :view="upload4area.view"
                    :height="350"
                    :no-circle="true"
                    :no-rotate="false"
                    lang-type="zh"
                    :max-size="200"
                  />
                </div>
              </el-col>
              <el-col :span="12">
                <div class="add-image">
                  <div class="add-image-title">
                    <span>上传首页图片</span>
                  </div>
                  <image-upload
                    ref="upload4home"
                    :key="upload4area.imagecropperKey"
                    v-model="form.homeImg"
                    :preview-id="form.homeImg"
                    :forever="true"
                    :width="702"
                    :view="upload4area.view"
                    :height="246"
                    :no-circle="true"
                    :no-rotate="false"
                    lang-type="zh"
                    :max-size="200"
                  />
                </div>
              </el-col>
            </el-row>
          </el-form-item>
        </template>
        <el-form-item class="form-btns">
          <el-button type="primary" @click="onSubmit">修改</el-button>
          <el-button @click="handleCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-scrollbar>
    <select-template :visible.sync="templateVisible" @select="selectTemplte" />
  </div>
</template>

<script>
import ptflb from '../components/ptflb'
import ptdhq from '../components/ptdhq'
import ptthq from '../components/ptthq'
import jdflb from '../components/jdflb'
import hfflb from '../components/hfflb'
import SelectTemplate from '../components/template/index'
import { get, getConfigByName, update } from '../api/index'

export default {
  name: 'DerectionalUpdate',
  components: { ptflb, ptdhq, ptthq, jdflb, hfflb, SelectTemplate },
  data() {
    return {
      templateVisible: false,
      upload4area: {
        viewId: '',
        view: '/API-DOCUMENT/document/file/download?id=',
        imagecropperKey: 0
      },
      form: {
        id: '',
        giveName: '',
        areaName: '',
        imageType: '0',
        storeName: '',
        classifType: '',
        dataId: '',
        areaImg: '',
        homeImg: ''
      },
      rules: {
        giveName: [
          { required: true, message: '请输入发放名称', trigger: 'blur' }
        ],
        areaName: [
          { required: true, message: '请输入专区名称', trigger: 'blur' }
        ],
        storeName: [
          { required: true, message: '请选择商城', trigger: 'blur' }
        ],
        classifType: [{
          required: true,
          message: '请选择福利类型',
          trigger: 'change'
        }]
      },
      mallTypes: [
      ],
      ptTypes: [
      ],
      jdTypes: [
      ],
      hfTypes: [],
      subForm: {},
      id: '',
      useRange: ''
    }
  },
  created() {
    this.id = this.$route.query.id
    this.getInfo()
  },
  methods: {
    /**
     * 选择模板
     * @param json
     */
    selectTemplte(json) {
      try {
        const obj = JSON.parse(json)
        this.form.areaImg = obj[0].content
        this.form.homeImg = obj[1].content
      } catch (err) {
        this.$message({
          title: '提示',
          message: '模板数据有误，请重试！',
          type: 'error',
          duration: 1500
        })
        return
      }
      this.templateVisible = false
    },
    handleCancel() {
      this.$router.push({
        path: this.$filterPath('index'),
        query: { t: this.$route.query.t }
      })
    },
    /**
     * 提交
     */
    onSubmit() {
      this.$refs['form'].validate(async(valid) => {
        if (valid) {
          if (this.form.classifType === '0') {
            this.subForm = await this.$refs['ptflbForm'].validateForm()
            if (this.subForm === '') {
              return
            }
            delete this.subForm.merchant
            if (new Date(this.subForm.receiveEndtime).getTime() < new Date().getTime()) {
              this.$message({
                message: '福利领取结束时间不得小于当前时间！',
                type: 'warning'
              })
              return
            }
            if (new Date(this.subForm.expirationDate).getTime() < new Date().getTime()) {
              this.$message({
                message: '福利使用结束时间不得小于当前时间！',
                type: 'warning'
              })
              return
            }
            if (new Date(this.subForm.receiveStarttime).getTime() > new Date(this.subForm.receiveEndtime).getTime()) {
              this.$message({
                message: '福利领取开始时间不得大于福利领取结束时间！',
                type: 'warning'
              })
              return
            }
            if (new Date(this.subForm.expirationStartdate).getTime() > new Date(this.subForm.expirationDate).getTime()) {
              this.$message({
                message: '福利使用开始时间不得大于福利使用结束时间！',
                type: 'warning'
              })
              return
            }
            if (new Date(this.subForm.expirationStartdate).getTime() < new Date(this.subForm.receiveStarttime).getTime()) {
              this.$message({
                message: '福利使用开始时间不得小于福利领取开始时间！',
                type: 'warning'
              })
              return
            }
            if (new Date(this.subForm.expirationDate).getTime() < new Date(this.subForm.expirationStartdate).getTime()) {
              this.$message({
                message: '福利使用结束时间不得小于福利领取结束时间！',
                type: 'warning'
              })
              return
            }
            // 如果是线下使用，则删除关于专区的相关配置
            if (this.subForm.useRange === '2') {
              delete this.form.areaName
              delete this.form.imageType
              delete this.form.areaImg
              delete this.form.homeImg
            } else if (this.subForm.useRange === '1') { // 如果更改为线上支付，删除线下支付商户信息
              delete this.subForm.fuMerchant
            }
          } else if (this.form.classifType === '1') {
            this.subForm = await this.$refs['ptdhqForm'].validateForm()
            if (this.subForm === '') {
              return
            }
            if (new Date(this.subForm.receiveEndtime).getTime() < new Date().getTime()) {
              this.$message({
                message: '兑换券领取结束时间不得小于当前时间！',
                type: 'warning'
              })
              return
            }
            if (new Date(this.subForm.expirationDate).getTime() < new Date().getTime()) {
              this.$message({
                message: '兑换券已过期，请选择其他兑换券！',
                type: 'warning'
              })
              return
            }
          } else if (this.form.classifType === '2') {
            this.subForm = await this.$refs['jdflbForm'].validateForm()
            if (this.subForm === '') {
              return
            }
            if (new Date(this.subForm.receiveEndtime).getTime() < new Date().getTime()) {
              this.$message({
                message: '京东活动开始结束时间不得小于当前时间！',
                type: 'warning'
              })
              return
            }
            if (new Date(this.subForm.expirationDate).getTime() < new Date().getTime()) {
              this.$message({
                message: '京东活动已结束，请选择其他活动！',
                type: 'warning'
              })
              return
            }
          } else if (this.form.classifType === '7') {
            this.subForm = await this.$refs['ptthqForm'].validateForm()
            if (this.subForm === '') {
              return
            }
            if (new Date(this.subForm.receiveEndtime).getTime() < new Date().getTime()) {
              this.$message({
                message: '活动开始结束时间不得小于当前时间！',
                type: 'warning'
              })
              return
            }
            if (new Date(this.subForm.expirationDate).getTime() < new Date().getTime()) {
              this.$message({
                message: '活动已结束，请选择其他活动！',
                type: 'warning'
              })
              return
            }
            this.subForm.userUpperLimit = 1
          } else if (this.form.classifType === '8') {
            this.subForm = await this.$refs['hfflbForm'].validateForm()
            if (this.subForm === '') {
              return
            }
            if (new Date(this.subForm.receiveEndtime).getTime() < new Date().getTime()) {
              this.$message({
                message: '惠福专区活动开始结束时间不得小于当前时间！',
                type: 'warning'
              })
              return
            }
            if (new Date(this.subForm.expirationDate).getTime() < new Date().getTime()) {
              this.$message({
                message: '惠福专区活动已结束，请选择其他活动！',
                type: 'warning'
              })
              return
            }
          }
          this.updateData()
        }
      })
    },
    updateData() {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      const params = Object.assign(this.form, this.subForm)
      return new Promise((resolve, reject) => {
        update(params).then((res) => {
          loading.close()
          if (res.data.code === '200') {
            this.$message({
              title: '成功',
              message: '修改成功',
              type: 'success',
              duration: 2000
            })
            this.handleCancel()
          } else {
            this.$message({
              title: '失败',
              message: res.data.msg || '修改失败',
              type: 'error',
              duration: 2000
            })
          }
        }).catch(error => {
          loading.close()
          reject(error)
        })
      })
    },
    getInfo() {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        get(this.id).then(async res => {
          loading.close()
          const data = res.data.data
          const str = data.classifType
          if (str.indexOf('0') > -1 || str.indexOf('1') > -1 || str.indexOf('7') > -1) {
            this.mallTypes.push({
              name: '平台商城',
              id: 1
            })
          }
          if (str.indexOf('0') > -1) {
            this.ptTypes.push({
              name: '福利包',
              id: '0'
            })
          }
          if (str.indexOf('2') > -1) {
            this.mallTypes.push({
              name: '京东商城',
              id: 2
            })
            this.jdTypes.push({
              name: '福利包',
              id: '2'
            })
          }
          if (str.indexOf('1') > -1) {
            this.ptTypes.push({
              name: '兑换券',
              id: '1'
            })
          }
          if (str.indexOf('7') > -1) {
            this.ptTypes.push({
              name: '线下提货券',
              id: '7'
            })
          }
          if (str.indexOf('8') > -1) {
            this.mallTypes.push({
              name: '惠福商城',
              id: 3
            })
            this.hfTypes.push({
              name: '福利包',
              id: '8'
            })
          }
          for (const i in data) {
            if (this.form.hasOwnProperty(i)) {
              this.form[i] = data[i]
            } else {
              this.$set(this.subForm, i, data[i])
            }
          }
          // 由于线下提货券的优惠券名称与其他类型中的专区名称字段一致，需要特殊判断并赋值
          if ((data.classifType === '7' || data.classifType === '8') && data.areaName) {
            this.$set(this.subForm, 'areaName', data.areaName)
          }
          // 京东福利包(京东活动)和平台提货券(商户白名单)用到dataId
          if (data.classifType === '2' || data.classifType === '7' || data.classifType === '8') {
            this.$set(this.subForm, 'dataId', data.dataId)
          }
          if (this.form.classifType === '2') {
            this.form.storeName = 2
          } else if (this.form.classifType === '8') {
            this.form.storeName = 3
          } else {
            this.form.storeName = 1
          }
          // this.form.storeName = this.form.classifType === '2' ? 2 : 1
        }).catch(error => {
          loading.close()
          reject(error)
        })
      })
    },
    /**
     * 监听
     * @param range
     */
    useRangeChange(range) {
      this.useRange = range
    }
  }
}
</script>

<style scoped lang="scss">
.derectional-update-page {
  padding: 10px;

  .classify-scrollbar {
    background-color: #fff;
    margin-top: 10px;

    .create-title {
      position: relative;
      height: 40px;
      line-height: 40px;
      padding: 0 20px;
      background-color: #ffffff;
      border-bottom: 1px solid #e5e5e5;
      font-family: PingFangSC-Medium;
      font-weight: bold;
      color: rgba(51, 51, 51, 1);
      font-size: 14px;

      &:before {
        content: "";
        position: absolute;
        width: 2px;
        @include bg-color($mainColor);
        top: 13px;
        bottom: 13px;
        left: 15px;
      }
    }

    .create-form {
      width: 1000px !important;
      margin: 20px auto 0;

      .el-select {
        width: 100%;
      }

      .form-btns {
        text-align: center;
      }
    }

    .add-image {
      border: 1px solid #e5e5e5;
      padding: 0 20px 20px;
      border-radius: 4px;

      .add-image-title {
        display: flex;
        align-items: center;
        justify-content: space-between;

        & > span {
          color: #666;
          font-size: 14px;
        }
      }

      .add-image-main {
        display: inline-block;
        position: relative;
        background: #f7f7f8;
        border-radius: 4px;
        margin-bottom: 10px;

        .el-image {
          display: block;
        }

        &:hover {
          border-color: #fe5a61;
        }

        .icon-wrap {
          width: 300px;
          height: 180px;
          display: flex;
          align-items: center;
          justify-content: center;
          background: rgba(247, 247, 248, 1);
          border: 1px solid rgba(226, 227, 232, 1);
          border-radius: 4px;

          .avatar-uploader-icon {
            font-size: 48px;
            color: #dadada;
            width: 300px;
            text-align: center;
          }
        }

        img {
          display: block;
          max-width: 400px;
          border-radius: 4px;
        }
      }
    }
  }

}

</style>
